import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Radio,
  Space,
  Button,
  Upload,
  Modal,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import styles from './index.module.scss'
import Channel from 'components/Channel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { baseURL } from 'utils/request'
import { addArticle } from 'api/article'
export default class ArticlePublish extends Component {
  state = {
    type: 1,
    // 存放上传的文件列表
    fileList: [],
    showPreview: false,
    previewUrl: '',
  }
  formRef = React.createRef()
  render() {
    const { previewUrl, showPreview } = this.state
    return (
      <div className={styles.ArticleList}>
        <Card
          title={
            <Breadcrumb separator="/">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                <Link to="/home/list">文章列表</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>发布文章</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            labelCol={{ span: 4 }}
            initialValues={{ type: this.state.type, content: '' }}
            onFinish={this.onFinish}
            size="large"
            validateTrigger={['onBlur', 'onChange']}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '文章的标题不能为空',
                },
              ]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[
                {
                  required: true,
                  message: '请选择频道',
                },
              ]}
            >
              <Channel></Channel>
            </Form.Item>
            <Form.Item label="封面">
              <Form.Item name="type">
                <Radio.Group onChange={this.changeImageType}>
                  <Radio value={0}>无图</Radio>
                  <Radio value={1}>单图</Radio>
                  <Radio value={3}>三图</Radio>
                  {/* <Radio value={-1}>自动</Radio> */}
                </Radio.Group>
              </Form.Item>
              {this.state.type !== 0 && (
                <Upload
                  action={`${baseURL}upload`}
                  listType="picture-card"
                  name="image"
                  onChange={this.uploadImages}
                  fileList={this.state.fileList}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {this.state.fileList.length < this.state.type && (
                    <PlusOutlined></PlusOutlined>
                  )}
                </Upload>
              )}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[
                {
                  required: true,
                  message: '请输入文章内容',
                },
              ]}
            >
              <ReactQuill
                theme="snow"
                placeholder="请输入文章内容..."
              ></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  发布文章
                </Button>
                <Button size="large" onClick={this.addDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        {/* 弹窗，用于显示预览的图片 */}
        <Modal
          visible={showPreview}
          title="图片预览"
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewUrl} />
        </Modal>
        <Modal></Modal>
      </div>
    )
  }
  //上传校验
  beforeupload = (file) => {
    if (file.size >= 1024 * 500) {
      message.warn('上传的文件不能超过500kb')
      return false
    }
    if (!['image/png', 'image/jpeg'].includes(file.type)) {
      message.warn('只能上传jpg或者png的图片')
      return Upload.LIST_IGNORE
    }
    return true
  }
  // 注意：如果fileList是将来回显的，通过url就能够访问到
  // 如果fileList的文件是上传的，，，需要通过file.response.data.url
  handlePreview = (file) => {
    console.log(file)
    const url = file.url || file.response.data.url
    this.setState({
      showPreview: true,
      previewUrl: url,
    })
  }
  handleCancel = () => {
    this.setState({ showPreview: false, previewUrl: '' })
  }

  // save = async (values, draft) => {
  //   const { type, fileList } = this.state
  //   console.log(values)
  //   // 图片校验
  //   if (type !== fileList.length) {
  //     return message.warn('上传的图片数量不对')
  //   }
  //   const images = fileList.map((item) => {
  //     return item.url || item.response.data.url
  //   })
  //   //添加文章
  //   const res = await addArticle({
  //     ...values,
  //     cover: {
  //       type,
  //       images,
  //     },
  //     draft,
  //   })
  //   console.log(res)
  //   message.success('添加文章成功')
  //   this.props.history.push('/home/list')
  // }
  async save(values, draft) {
    const { fileList, type } = this.state
    if (fileList.length !== type) {
      return message.warn('上传的图片数量不正确')
    }
    // 根据fileList得到
    const images = fileList.map((item) => {
      return item.url || item.response.data.url
    })
    console.log(images)
    // 添加文章
    await addArticle(
      {
        ...values,
        cover: {
          type,
          images,
        },
      },
      draft
    )
    message.success('添加成功')
    this.props.history.push('/home/list')
  }
  onFinish = async (values) => {
    this.save(values, false)
  }
  //存入草稿
  // addDraft = async () => {
  //   // 获取表单的数据
  //   const values = await this.formRef.current.validateFields()
  //   this.save(values, true)
  // }
  addDraft = async () => {
    const values = await this.formRef.current.validateFields()
    this.save(values, true)
  }
  changeImageType = (e) => {
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }
  uploadImages = ({ fileList }) => {
    this.setState({
      fileList,
    })
  }
}
